from flask import abort, jsonify
from flask import request
from flask import session

from info.constants import HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.utils.response_code import RET, error_map
from . import home_blu

from flask import current_app, render_template


# 2. 使用蓝图注册路由
@home_blu.route('/')
def index():
    # 判断用户是否登陆 取出session中的user_id
    user_id = session.get('user_id')
    user = None  # type:User
    print(1)
    if user_id:
        try:
            user = User.query.get(user_id)
        except BaseException as e:
            current_app.logger.error(e)

    # 按照点击量查询排行强10的新闻数据
    print(2)
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)

    news_list = [news.to_basic_dict() for news in news_list]
    # 查询所有分类的数据传入模板
    print(3)
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    # 转换用户数据
    print(4)
    user = user.to_dict() if user else None
    return render_template('index.html', user=user, news_list=news_list, categories=categories)


# 设置网站小图标
@home_blu.route('/favicon.ico')
def favicon():
    # 返回一张图标图片
    # flask内置了语法,可以返回静态文件
    return current_app.send_static_file('news/favicon.ico')


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid')
    cur_page = request.args.get('cur_page')
    per_count = request.args.get('per_count', HOME_PAGE_MAX_NEWS)
    # 校验参数
    print(5)
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 格式转换
    print(6)
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    print(7)
    # 判断分类是否为最新
    filter_list = []
    if cid != 1:
        filter_list.append(News.category_id == cid)
    # 按照分类和页码获取新闻数据  发布时间倒叙
    print(8)
    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    print(9)
    # 包装到json中返回
    data = {
        "news_list": [news.to_dict() for news in pn.items],
        "total_page": pn.pages
    }
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
